package org.lztvn.elearning.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.lztvn.elearning.entities.User;

public class UserDaoImpl implements IUserDao {
	@PersistenceContext
	private EntityManager em;
	@Override
	public Long addUser(User u) {
		em.persist(u);
		return u.getIdUser();
	}

	@Override
	public void deleteUser(Long idUser) {
		User u = em.find(User.class, idUser);
		em.remove(u);
	}

	@Override
	public void modifierUser(User u) {
	  em.merge(u);
	}

	@Override
	public List<User> login(String username,String password) {
		Query req = em
				.createQuery("select u from User u where u.username = :x and u.password = :y");
		req.setParameter("x",username);
		req.setParameter("y",password);
		return req.getResultList();
	}

	@Override
	public List<User> listUser() {
		Query req = em.createQuery("select u from User u");
		return req.getResultList();
	}
	
	
	@Override
	public User getUser(Long idUser) {
		return em.find(User.class, idUser);
	}

	@Override
	public User getUserByUsername(String userName) {
		Query req = em
				.createQuery("select u from User u where u.username = :x");
		req.setParameter("x",userName);
		
		return (User)req.getResultList().get(0);
	}

	@Override
	public List<User> listTeacher() {
		Query req = em.createQuery("select u from User u where u.typeUser ='teacher'");
		return req.getResultList();
	}
}
